package com.example.netty.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

@Slf4j
public class MyHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端连接，channelId:{}", ctx.channel().id());

        MyManager.add(ctx.channel().id().asShortText(), ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端断开，channelId:{}", ctx.channel().id());

        MyManager.remove(ctx.channel().id().asShortText());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //首次连接是FullHttpRequest
        if (msg instanceof FullHttpRequest) {
            InetSocketAddress clientSocket = (InetSocketAddress) ctx.channel().remoteAddress();
            log.info("客户端连接，channelId:{}，ip:{}", ctx.channel().id(), clientSocket.getAddress().getHostAddress());

            FullHttpRequest request = (FullHttpRequest) msg;
            log.info("客户端连接，channelId:{}，uri:{}", ctx.channel().id(), request.uri());
        } else if (msg instanceof TextWebSocketFrame) {
            //正常的TEXT消息类型
            TextWebSocketFrame frame = (TextWebSocketFrame) msg;
            log.info("客户端发来文本消息，channelId:{}，内容：{}", ctx.channel().id(), frame.text());
        } else if (msg instanceof BinaryWebSocketFrame) {
            log.info("客户端发来流消息，channelId:{}", ctx.channel().id());
        }
        super.channelRead(ctx, msg);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {

    }

}
